import requests
import json

class CozeBot:
    def __init__(self, api_key, bot_id):
        self.api_key = api_key
        self.bot_id = bot_id
        self.base_url = "https://www.coze.com/api/v1"  # 请替换为实际的 API 地址
        self.headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
    
    def send_message(self, message):
        """发送消息到 Coze 机器人并获取响应"""
        endpoint = f"{self.base_url}/chat/completions"
        
        payload = {
            "bot_id": self.bot_id,
            "messages": [{
                "role": "user",
                "content": message
            }]
        }
        
        try:
            response = requests.post(
                endpoint,
                headers=self.headers,
                json=payload
            )
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            print(f"发送消息时出错: {e}")
            return None

def main():
    # 配置你的 API 密钥和机器人 ID
    API_KEY = "your_api_key_here"
    BOT_ID = "your_bot_id_here"
    
    # 创建机器人实例
    bot = CozeBot(API_KEY, BOT_ID)
    
    # 简单的对话循环
    print("开始与 Coze 机器人对话 (输入 'quit' 退出)")
    
    while True:
        user_input = input("你: ")
        if user_input.lower() == 'quit':
            break
            
        response = bot.send_message(user_input)
        if response:
            bot_reply = response.get("choices", [{}])[0].get("message", {}).get("content", "无响应")
            print(f"机器人: {bot_reply}")

if __name__ == "__main__":
    main()
